package com.example.demo.verticle

import com.example.demo.factory.createRouter
import io.vertx.core.http.HttpServer
import io.vertx.core.json.JsonObject
import io.vertx.kotlin.coroutines.CoroutineVerticle
import io.vertx.kotlin.coroutines.awaitResult
import org.slf4j.LoggerFactory


/**
 * @author Xu Haidong
 * @date 2023/4/20 10:52
 */
class HttpServerVerticle : CoroutineVerticle() {

  private val logger = LoggerFactory.getLogger(this.javaClass)

  override suspend fun start() {
    super.start()
    logger.info("初始化web服务")
    val localMap = vertx.sharedData().getLocalMap<String, JsonObject>("demo")
    val serverConfig = localMap["config"]?.getJsonObject("server")
    val vp = serverConfig?.getInteger("port")
    val port = if (vp is Int) vp else 8080
    try {
      val router = createRouter(vertx)
      awaitResult<HttpServer> { vertx.createHttpServer().requestHandler(router).listen(port, it) }
      logger.info("HTTP server started on port 8888")
    } catch (e: Exception) {
      logger.error(e.message, e)
    }
  }

  override suspend fun stop() {
    super.stop()
  }


}
